<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import { fetchGoodSendList } from '@/api/goodSend'
import { formatDateTime } from '@/utils/dayjs'
import { getSendStatus } from '@/constants/sendSatus'
import ViewSend from './components/ViewSend.vue'
import { exportShippingOrderToExcel } from '@/utils/exportShippingOrder' // 新增导入

// 列表 & 分页
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const dialogVisible = ref(false)
const selectedOrder = ref(null)
const exportLoading = ref(false) // 新增导出loading状态

const cancelDialogVisible = ref(false)
const cancelOrder = ref(null)
// 请求参数
const requestParams = ref({
  currentPage: 1,
  pageSize: 10,
  queryFields: {
    sendNo: '',
    sendTime: [], // 用于el-date-picker绑定
    sendTimeBegin: '',
    sendTimeEnd: '',
    mobilphone: '',
  },
})

// 获取数据
const fetchOrderData = async () => {
  try {
    loading.value = true
    const params = {
      ...requestParams.value,
      queryFields: {
        sendNo: requestParams.value.queryFields.sendNo.trim() || null,
        sendTimeBegin:
          requestParams.value.queryFields.sendTime && requestParams.value.queryFields.sendTime[0]
            ? `${requestParams.value.queryFields.sendTime[0]} 00:00:00`
            : null,
        sendTimeEnd:
          requestParams.value.queryFields.sendTime && requestParams.value.queryFields.sendTime[1]
            ? `${requestParams.value.queryFields.sendTime[1]} 23:59:59`
            : null,
        mobilphone: requestParams.value.queryFields.mobilphone.trim() || null,
      },
    }
    const res = await fetchGoodSendList(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取已发货订单失败')
    }
  } catch (error) {
    logger.error('获取已发货订单失败', error)
    ElMessage.error('获取已发货订单失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  requestParams.value.currentPage = 1
  fetchOrderData()
}

// 重置
const resetSearch = () => {
  requestParams.value.queryFields.sendNo = ''
  requestParams.value.queryFields.sendTime = []
  requestParams.value.queryFields.mobilphone = ''
  requestParams.value.currentPage = 1
  fetchOrderData()
}

// 详情
const handleViewDetails = (row) => {
  selectedOrder.value = row
  dialogVisible.value = true
}

// 新增：导出Excel功能
const handleExportExcel = async () => {
  if (!selectedOrder.value) {
    ElMessage.error('没有可导出的发货单数据')
    return
  }

  try {
    exportLoading.value = true
    await exportShippingOrderToExcel(selectedOrder.value)
    ElMessage.success('发货单导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error(error.message || '导出发货单失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 新增：表格行导出按钮事件
const handleExportRow = (row) => {
  selectedOrder.value = row
  handleExportExcel()
}

const handleCancelOrder = (row) => {
  cancelOrder.value = row
  cancelDialogVisible.value = true
}

const handleCancelDialogClose = () => {
  cancelDialogVisible.value = false
  cancelOrder.value = null
}

// 挂载
onMounted(() => {
  fetchOrderData()
})

// 分页事件
const handleSizeChange = (val) => {
  requestParams.value.pageSize = val
  requestParams.value.currentPage = 1
  fetchOrderData()
}

const handleCurrentChange = (val) => {
  requestParams.value.currentPage = val
  fetchOrderData()
}
</script>

<template>
  <!-- 更新模态框：添加自定义header和导出按钮 -->
  <el-dialog
    v-model="dialogVisible"
    append-to-body
    align-center
    destroy-on-close
    title="发货单详情"
    width="80%"
  >
    <!-- 自定义header，包含导出按钮 -->
    <template #header="{ titleId, titleClass }">
      <div class="flex items-center justify-between w-full">
        <span :id="titleId" :class="titleClass">发货单详情</span>
        <el-button
          type="primary"
          size="small"
          @click="handleExportExcel"
          :loading="exportLoading"
          :disabled="!selectedOrder"
        >
          <template #icon>
            <el-icon><LineMdDownload /></el-icon>
          </template>
          导出发货单
        </el-button>
      </div>
    </template>

    <ViewSend :send-info="selectedOrder" />
  </el-dialog>

  <el-dialog
    v-model="cancelDialogVisible"
    append-to-body
    align-center
    destroy-on-close
    title="作废发货单"
    width="80%"
  >
    <ViewSend
      :send-info="cancelOrder"
      :show-cancel-footer="true"
      @cancel="handleCancelDialogClose"
      @success="
        () => {
          handleCancelDialogClose()
          fetchOrderData()
        }
      "
    />
  </el-dialog>

  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="requestParams.queryFields" @submit.prevent="handleSearch">
          <el-form-item label="发货单号">
            <el-input
              v-model="requestParams.queryFields.sendNo"
              placeholder="请输入发货单号"
              clearable
              style="width: 180px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="发货时间">
            <el-date-picker
              v-model="requestParams.queryFields.sendTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 260px"
              clearable
            />
          </el-form-item>
          <el-form-item label="收货人手机号">
            <el-input
              v-model="requestParams.queryFields.mobilphone"
              placeholder="请输入收货人手机号"
              clearable
              style="width: 180px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="table-container">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" height="100%">
        <el-table-column prop="sendNo" label="发货单号" min-width="200" align="center" />
        <el-table-column prop="sendTime" label="发货时间" min-width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.sendTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="sendState" label="发货状态" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getSendStatus(row.sendState)?.type || 'info'">
              {{ getSendStatus(row.sendState)?.text || '未知状态' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="xzqhName" label="行政区划" min-width="150" align="center" />
        <el-table-column prop="consignee" label="收货人" min-width="120" align="center" />
        <el-table-column prop="mobilphone" label="手机号" min-width="150" align="center" />
        <el-table-column
          prop="address"
          label="详细地址"
          min-width="250"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column prop="expressCompanyname" label="快递公司" width="120" align="center" />
        <el-table-column prop="trackingNumber" label="快递单号" width="200" align="center" />
        <el-table-column prop="dealerOperator" label="操作员" min-width="120" align="center" />

        <el-table-column label="操作" width="320" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetails(row)">
              <template #icon>
                <el-icon><LineMdWatchLoop /></el-icon>
              </template>
              查看详情
            </el-button>
            <!-- 在表格中也添加导出按钮 -->
            <el-button
              type="success"
              size="small"
              @click="handleExportRow(row)"
              style="margin-left: 10px"
            >
              <template #icon>
                <el-icon><LineMdDownload /></el-icon>
              </template>
              导出
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleCancelOrder(row)"
              style="margin-left: 10px"
              :disabled="row.sendState === 2"
            >
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              作废
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="requestParams.currentPage"
          v-model:page-size="requestParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;
    .el-table {
      flex: 1;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
